294: Web Server

Web Server

Introduction

The goal here was just to create a lightweight http server from scratch. Why from scratch? No reason other than a pathological desire to reinvent the wheel. As it progressed a basic feature list emerged:

Github

The github for the webserver is here and the website is here

Getting HTTP requests with ZMQ

-Intro

If you don't know what ZMQ is, its a great wrapper for standard sockets and supports a bunch of different protocols and sockets types. See their website here. That being said, ZMQ is far from the best way to do this. I just wanted an excuse to use ZMQ outside of research/work.

-Basic ZMQ

ZMQ requires a context be constructed to do anything


    void *ctx = zmq_ctx_new ();
    assert (ctx);
    

And then, a socket, using that context. The different socket types can be read about here on the socket page


    void *socket = zmq_socket (ctx, ZMQ_STREAM);
    assert (socket);
    

Binding takes a string which specifies both the protocol and the ip/port. The code below specifies any adapter on port 80(which is the port for http). This returns an error code which should probably be checked. The different protocols can be read about here on the bind page


    int rc = zmq_bind (socket, "tcp://*:80");
    assert (rc == 0);
    

Now that you have a socket constructed and bound, there are two basic ways to send and receive, buffers and zmq_msg. You'll see me intermix them as buffers are faster but have a fixed size while messages adapt to the size of the incoming message. To use messages, they must be initialized first. Here I initialize two messages, one will receive the ID of the sender, and the other the content of the message. This is just how ZMQ handles stream sockets.


    zmq_msg_t id,req;
    zmq_msg_init(&id);
    zmq_msg_init(&req);
    


    zmq_msg_t id,req;
    zmq_msg_init(&id);
    zmq_msg_init(&req);